package com.chat.demo.userservice.Entity.DAO;

import com.chat.demo.userservice.DTO.FriendShip.FriendInfo;
import com.chat.demo.userservice.DTO.FriendShip.FriendRequestDTO;
import org.apache.ibatis.annotations.*;

import java.util.List;

@Mapper
public interface FriendshipDao {

    @Insert("INSERT INTO app.friend_request (sender_id, recipient_id, created_at) " +
            "VALUES (#{senderId}, #{receiverId}, now())")
    void createFriendRequest(@Param("senderId") Long sender_id, @Param("receiverId") Long receiver_id);

    // 1️.查询请求中的发送者和接收者 ID
    @Select("SELECT sender_id, recipient_id FROM app.friend_request WHERE request_id = #{requestId}")
    FriendRequestDTO getSenderIdAndReceiverId(@Param("requestId") Long requestId);

    // 2️.删除请求记录
    @Delete("DELETE FROM app.friend_request WHERE request_id = #{requestId}")
    void deleteFriendRequestById(@Param("requestId") Long requestId);

    // 3️.插入好友关系（自动排序）
    @Insert("INSERT INTO app.friendship (user_id1, user_id2, status) " +
            "VALUES (LEAST(#{userId1}, #{userId2}), GREATEST(#{userId1}, #{userId2}), 'active')")
    void insertFriendship(@Param("userId1") Long userId1, @Param("userId2") Long userId2);

    @Delete("DELETE FROM app.friend_request WHERE request_id = #{requestId}")
    void rejectFriendRequest(@Param("requestId") Long requestId);

    @Delete("DELETE FROM app.friendship WHERE (user_id1 = #{myId} AND user_id2 = #{brokeId}) OR (user_id2 = #{brokeId} AND user_id1 = #{myId})")
    void deleteFriendshipById(@Param("myId") Long myId, @Param("brokeId") Long brokeId);

    @Select("SELECT EXISTS (SELECT 1 FROM app.friendship WHERE (user_id1 = #{userIdA} AND user_id2 = #{userIdB}) OR (user_id1 = #{userIdB} AND user_id2 = #{userIdA}) AND status = 'active')")
    boolean isFriends(@Param("userIdA") Long userIdA, @Param("userIdB") Long userIdB);

    @Select("SELECT " +
            "    CASE " +
            "        WHEN user_id1 = #{userId} " +
            "        THEN user_id2 " +
            "        ELSE user_id1 " +
            "    END AS friend_id, " +
            "    relationship_id, " +
            "    status, " +
            "    created_at, " +
            "    updated_at " +
            "FROM app.friendship " +
            "WHERE status = 'active' " +
            "AND (user_id1 = #{userId} OR user_id2 = #{userId})")
    List<FriendInfo> findActiveFriendsByUserId(@Param("userId") Long userId);

    @Select({
            "SELECT CASE WHEN user_id1 = #{userId} THEN user_id2 ELSE user_id1 END AS friend_id " +
            "FROM app.friendship " +
            "WHERE (user_id1 = #{userId} OR user_id2 = #{userId}) AND status = 'active'",
    })
    List<Long> findActiveFriendIdsByUserId(Long userId);
}